package com.whjfxx.terminal.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.whjfxx.terminal.entity.User;
import com.whjfxx.terminal.exceptions.BizException;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by b.c on 2022/4/14 10:34
 */
public class JWTUtil {

    static final int EXPIRES = 1;

    static final String USER_ID = "userId";

    public static final String generateToken(User user) {
        String token = JWT.create()
                .withHeader(new HashMap<>())
                .withClaim(USER_ID, user.getId())
                .withExpiresAt(getExpires())
                .sign(Algorithm.HMAC256(user.getSecret()));
        return token;
    }

    public static final Long resolveToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("secret")).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            Claim userId = decodedJWT.getClaim(USER_ID);
            return userId.asLong();
        } catch (JWTVerificationException jwtVerificationException) {
            throw BizException.build("用户信息验证失败");
        }
    }

    /**
     * 获取过期时间
     * @return
     */
    private static Date getExpires() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, EXPIRES);
        return calendar.getTime();
    }

    public static void main(String[] args) throws InterruptedException {
        try {
            User user = new User();
            user.setId(1L);
            user.setUserName("1");
            user.setIco("ico");
            user.setSecret("secret");

            String token = generateToken(user);
            Thread.sleep(2000L);
            resolveToken(token);
        } catch (JWTVerificationException e) {
            System.out.println("验证失败");
        }
    }
}
